// pages/income/income.js
import { income, sum} from '../../api/index.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    sum: null,
    incomeList: [],
    type: 'machine_income',
    tabList: [
      {
        type: 'machine_income',
        name: '我的机器'
      },
      {
        type: 'install_machine_income',
        name: '我的安装'
      },
      {
        type: 'region_income',
        name: '我的区域'
      },
      {
        type: 'recommend_rmb',
        name: '推荐奖励'
      }
    ],
    installList: [
      {
        name: '机器收入'
      },
      {
        name: '系统使用费'
      }
    ],
    regionList: [
      {
        name: '收益明细'
      },
      {
        name: '服务商明细'
      }
    ]
  },

  onLoad: function(options) {
    const { type } = this.data
    this.getIncome(type)
    this.getSum(type)
  },

  onReady: function() {
    this.filterTabs()
  },

  // 获取收益类型
  getIncome: function(type) {
    income({ 'income_type': type})
    .then(res => {
      this.setData({
        incomeList: res.data
      })
      console.log(res, '88887777')
    })
    .catch(e => {
      console.log(e, '收益明细')
    })
  },

  // 切换收益类型
  onTabChange: function(e) {
    const {detail: {index, type}} = e

    this.setData({
      type
    },() => {
      this.getIncome(type)
      this.getSum(type)
    })
  },

  // 获取收益总数
  getSum: function(type) {
    sum({'income_type': type})
    .then(res => {
      this.setData({
        sum: res.data
      })
    })
    .catch(e => {
      console.log(e, '获取收益总数')
    })
  },

  navigateToWithdraw: function (e) {
    const {sum: {oxt_income: oxt, rmb_income: rmb}} = this.data
    const { currentTarget: { dataset: { type } } } = e
    console.log(this.data, 'with draw')
    wx.navigateTo({
      url: `/pages/withdrawal/withdrawal?type=${type}&rmb=${rmb}&oxt=${oxt}`,
    })
  },

  filterTabs: function() {
    let { tabList } = this.data
    const identity = wx.getStorageSync('identity')

    if (identity === 'OPERATION' || identity === 'BUYER') {
      tabList = tabList.filter(t => {
        return t.type !== 'region_income'
      })

      console.log(tabList, 'render tab list')

    }


    this.setData({
      tabList
    })
  }

})